package com.hanhai.material.device.controller;

import com.hanhai.material.common.result.Result;
import com.hanhai.material.common.result.ResultTool;
import com.hanhai.material.device.entity.SysBom;
import com.hanhai.material.device.entity.SysBomChild;
import com.hanhai.material.device.service.SysBomChildService;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.relation.RelationManager;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

import static com.hanhai.material.device.entity.table.SysBomChildTableDef.SYS_BOM_CHILD;

/**
 * 控制层。
 *
 * @author youchuang
 * @since 2023/10/18 11:26:03
 */
@RestController
@RequestMapping("/bom_child")
@Log4j2
public class SysBomChildController {

    @Autowired
    private SysBomChildService sysBomChildService;

    @PostMapping("/get/{materialId}")
    public Result<?> get(@PathVariable String materialId) {
        RelationManager.addIgnoreRelations("bomChildList", "bom");
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.where(SYS_BOM_CHILD.MATERIAL_ID.like(materialId));
        log.error("MaterialId:{}", queryWrapper.toSQL());
        List<SysBomChild> sysBomChildList = this.sysBomChildService.getMapper().selectListWithRelationsByQuery(queryWrapper);
        for (SysBomChild bomChild : sysBomChildList) {
            List<SysBom> bomList = new ArrayList<>();
            for (SysBom sysBom : bomChild.getBomList()) {
                if (sysBom.getWorkPlan() != null) {
                    bomList.add(sysBom);
                }
            }
            bomChild.setBomList(bomList);
        }
        return sysBomChildList.isEmpty() ? ResultTool.fail() : ResultTool.success(sysBomChildList);
    }

}
